/*Author: Rony Lahav (ID:043489889)*/

import java.util.Collection;
import java.util.TreeMap;


public class AVManagerSN extends AVManager implements Runnable{

	public void run() {
		TreeMap<String,DBTuple> peersForAV;
		do {
			// Get from the DB all of the online tuples to which I should send AV to
			peersForAV = (TreeMap<String,DBTuple>)DataBase.getInstance().getAllOnlineRegTuples();
			//run over all peers and send an AV message
			Collection<DBTuple> c = peersForAV.values();
			String AVmsg=createAVMessage();
			if (c.size()>0){	//at least 1 tuple is online
				for (DBTuple tuple : c) {
					if (final_project.isShutDown()) {
						break;
					}
					// Open a dedicated thread to send AV to one specific peer
					SingleUDPMessageSender singleAV = new SingleUDPMessageSender(final_project.mainUDPSoc, tuple, AVmsg, final_project.getNewUniqueID());
					Thread thread = new Thread(singleAV);
					final_project.addThreadToLivingList(singleAV.getUniqueID(), thread);
					thread.start();
				}
			}
			else{	//send AV to my SNs to keep me alive even if i don't have peers for propagation of messages
				SNsHandler.getInstance().propagateMessageToMySNs("#"+AVmsg, final_project.getMyKey());
			}
			
			try{
				// Sleep until next AV frequency
				Thread.sleep(final_project.frequency);
			}
			catch (InterruptedException e){}
		} while (!final_project.isShutDown());
	}
}
